/**
 *
 */
package siebes.rmi.sorter;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

/**
 * @author eddie
 *
 */
public class QuickSort extends UnicastRemoteObject implements ISorter {

    /**
     * Ivm Serializeableobject.
     */
    private static final long serialVersionUID = -7370404953889142503L;

    /**
     * Implementeer het quicksort algoritme.
     * @throws RemoteException rmi.
     */
    protected QuickSort() throws RemoteException {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * Lijst met comparable objecten.
     */
    @SuppressWarnings("rawtypes")
    private Comparable[] lijst;

    /**
     * moet buiten funktie staan.
     */
    private int number;

    /* (non-Javadoc)
     * @see siebes.rmi.sorter.ISorter#sort(java.lang.Comparable[])
     */
    @SuppressWarnings("rawtypes")
    @Override
    public final Comparable[] sort(final Comparable[] t) {
        this.lijst = t;
        this.number = t.length;
        quicksort(lijst, 0, number - 1);
        return lijst;
    }

    /**
     * @param list lijst om te sorteren.
     * @param low laagste element.
     * @param high hoogste element.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void quicksort(final Comparable[] list,
                final int low, final int high) {
        int i = low, j = high;
        Comparable pivot = list[low + (high - low) / 2];
        while (i <= j) {
            while (list[i].compareTo(pivot) < 0) {
                i++;
            }
            while (list[j].compareTo(pivot) > 0) {
                j--;
            }
            if (i <= j) {
                exchange(i, j);
                i++;
                j--;
            }
        }
        if (low < j) {
            quicksort(list, low, j);
        }
        if (i < high) {
            quicksort(list, i, high);
        }
      }

    /**
     * verwissel 2 comparables in array lijs[].
     * @param i index van Lijst
     * @param j Index van Lijst
     */
    @SuppressWarnings("rawtypes")
    private void exchange(final int i, final int j) {
        Comparable temp = lijst[i];
        lijst[i] = lijst[j];
        lijst[j] = temp;
    }

}
